<template>
  <div class="blog-toc-container">
    <h2>目录</h2>
    <RightList :list="tocWithSelect" @select="handleSelect"></RightList>
  </div>
</template>

<script>
import RightList from "./RightList.vue"
import { debounce } from "@/utils"
export default {
  components: {
    RightList
  },
  props: {
    toc: {
      type: Array
    }
  },
  methods: {
    handleSelect(item) {
      location.hash = item.anchor
    },
    setSelect(scrollDom) {
      if (!scrollDom) return
      this.activeAnchor = ""
      const range = 300
      for(const dom of this.doms) {
        if (!dom) {
          continue
        }
        const top = dom.getBoundingClientRect().top
        if (top >= 0 && top <= range) {
          this.activeAnchor = dom.id
          return
        } else if (top > range) {
          return
        } else {
          this.activeAnchor = dom.id
        }
      }
    }
  },
  data() {
    return {
      activeAnchor: ""
    }
  },
  computed: {
    tocWithSelect() {
        const getToc = (toc = []) => {
          return toc.map(t => ({
            ...t,
            isSelect: t.anchor === this.activeAnchor,
            children: getToc(t.children)
          }))
        }
      return getToc(this.toc)
    },
    doms() {
      const doms = []
      const addToDoms = toc => {
        for (const t of toc) {
          doms.push(document.getElementById(t.anchor))
          if (t.children && t.children.length) {
            addToDoms(t.children)
          }
        }
      }
      addToDoms(this.toc)
      return doms
    }
  },
  created() {
    this.setSelectDebounce = debounce(this.setSelect, 50)
    this.$bus.$on("mainScroll", this.setSelectDebounce)
  },
  beforeDestroy() {
    this.$bus.$off("mainScroll", this.setSelectDebounce)
  }
}
</script>

<style scoped lang="scss">
.blog-toc-container {
  h2 {
    font-weight: bold;
    letter-spacing: 2px;
    font-size: 1em;
    margin: 0;
  }
}
</style>